package com.learn.security.modules.security;

import com.learn.security.common.exception.InnerAuthenticationException;
import com.learn.security.modules.vo.UserDto;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * created by yuanjunjie on 2019/7/6 8:02 PM
 * @author lee
 */
@Slf4j
@UtilityClass
public class SecurityUtils {


    public UserDto getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            log.error("getAuthentication == null");
            throw new InnerAuthenticationException("authentication error");
        }
        LoginUser user = (LoginUser) authentication.getPrincipal();
        if (user.getUserDto() == null) {
            log.error("getAgentUserDto == null authentication=>{}", authentication);
            throw new InnerAuthenticationException("can't get agent userInfo");
        }
        return user.getUserDto();
    }
}
